//
//  BGSubmitViewController.swift
//  Billing
//
//  Created by Dale on 17/4/19.
//  Copyright © 2017年 Nari. All rights reserved.
//

import UIKit

class Model: NSObject {
    var title: String?
    var detail: String? //早上 中午 晚上 其它
    var type: Int
    init(title: String, detail: String, type: Int) {
        self.title = title
        self.detail = detail
        self.type = type
    }
}


class BGSubmitViewController: BCFatherViewController {
    
    var tmpMoney: String?
    var tmpBtn: UIButton?
    
    @IBOutlet weak var tableView: UITableView!
    lazy var dataSource = [Model]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        BmobManager.sumQuery { (result, status) -> (Void) in
            
        }
        
        self.title = "提交"
        Common.removeExtraCellLines(TableView: tableView)
        addDataSource()
    }
    
    func addDataSource() -> Void {
        let timeStr = Common.getCurrentTime();
        let typeDetail = Common.configureType(type: timeStr)
        let model = Model(title: "日期", detail: Common.getCurrentDate(), type: 0)
        let model1 = Model(title: "时间", detail: Common.getCurrentTime(), type: 0)
        let model2 = Model(title: "类型", detail: typeDetail, type: 0)
        let model3 = Model(title: "金额", detail: "0", type: 1)
        let model4 = Model(title: "", detail: "", type: 2)
        dataSource.append(model)
        dataSource.append(model1)
        dataSource.append(model2)
        dataSource.append(model3)
        dataSource.append(model4)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
}

extension BGSubmitViewController: UITableViewDataSource {
    public func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = dataSource[indexPath.row]
        let cell = BGSubmitCell.cellWithTableView(tableView: tableView, obj: model)
        cell.configureCell(model: model)
        self.tmpBtn = cell.submitBtn
        if tmpMoney != nil {
            cell.textField?.text = tmpMoney!
        }
        cell.clickClosure = { (money: String, type: Int)-> Void in
            if type == 1 {
                self.submitAction()
            } else {
                self.tmpMoney = money
            }
        }
        return cell
    }
    
    func submitAction() -> Void {
        view.endEditing(true)
        if tmpMoney == nil {
            SVProgressHUD.showError(withStatus: "请输入金额")
            return
        }
        
        if tmpMoney == "0" || tmpMoney == "" {
            SVProgressHUD.showError(withStatus: "请输入金额")
            return
        }
        
        if !AssistClass.isPureFloat(self.tmpMoney) {
            SVProgressHUD.showError(withStatus: "请输入纯数字")
            return
        }
        
        let num = NSString(string: self.tmpMoney!).floatValue
        let tmpStr = "\(num)"
        print(num)
        
        if !AssistClass.isValid(tmpStr) {
            SVProgressHUD.showError(withStatus: "最多输入两位小数")
            return
        }
        
        if num < 0.0 {
            SVProgressHUD.showError(withStatus: "请输入大于0的数字")
            return
        }
        
        if num > 1000.0 {
            SVProgressHUD.showError(withStatus: "请输入小于1000的数字")
            return
        }
        let model = Model(title: "金额", detail: tmpStr, type: 0)
        let tmpArr = [dataSource[0], dataSource[1], dataSource[2], model]
        
        let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[2] as! CustomAlterView
        customAlert.cellType = 1
        customAlert.typeClosure = { (str: String)-> Void in
            self.submitToNetwork()
        }
        customAlert.showAlertView()
        customAlert.tmpArr = tmpArr
        customAlert.tableView?.reloadData()
        
    }
    
    func submitToNetwork() -> Void {
        self.tmpBtn?.backgroundColor = UIColor.gray
        self.tmpBtn?.isEnabled = false
        let model = dataSource[2]
        var type: NSNumber?
        
        switch model.detail {
        case "早上"?:
            type = NSNumber(value: 0)
        case "中午"?:
            type = NSNumber(value: 1)
        case "晚上"?:
            type = NSNumber(value: 2)
        default:
            type = NSNumber(value: 3)
        }
        
        SVProgressHUD.show()
        BmobManager.queryOneRecord(dateStamp: dataSource[0].detail!, type: type!) { (result, status) -> (Void) in
            SVProgressHUD.dismiss(withDelay: 1.0, completion: {
                if status == .NRSSuccess {
                    BmobManager.submitRecord(userId: BmobUser.current().username, type: type!, timeStamp: self.dataSource[1].detail!, money: NSNumber(value: NSString(string: self.tmpMoney!).floatValue), dateStamp: self.dataSource[0].detail!) { (result, status) -> (Void) in
                        if status == .NRSSuccess {
                            self.tmpBtn?.backgroundColor = UIColor(red: 28.0/255, green: 202.0/255, blue: 147.0/255,alpha: 1)
                            self.tmpBtn?.isEnabled = true
                            SVProgressHUD.showSuccess(withStatus: "提交成功")
                            SVProgressHUD.dismiss(withDelay: 1.0, completion: {
                                self.dataSource.removeAll()
                                self.tmpMoney = "0"
                                self.addDataSource()
                                self.tableView.reloadData()
                            })
                            isRefrsh = true
                        } else {
                            self.tmpBtn?.backgroundColor = UIColor.gray
                            self.tmpBtn?.isEnabled = false
                            SVProgressHUD.showError(withStatus: result as! String)
                        }
                    }
                } else {
                    self.tmpBtn?.backgroundColor = UIColor(red: 28.0/255, green: 202.0/255, blue: 147.0/255,alpha: 1)
                    self.tmpBtn?.isEnabled = true
                    SVProgressHUD.showError(withStatus: result as! String)
                    SVProgressHUD.dismiss(withDelay: 1.0, completion: {
                        self.dataSource.removeAll()
                        self.tmpMoney = "0"
                        self.addDataSource()
                        self.tableView.reloadData()
                    })
                }
            })
        }
    }
    
}

extension BGSubmitViewController: UITableViewDelegate {
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        view.endEditing(true)
        let model = dataSource[indexPath.row]
        if indexPath.row == 0 {
            let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[0] as! CustomAlterView
            let locale = NSLocale(localeIdentifier: "zh_CN")
            customAlert.datePicker?.locale = locale as Locale
            customAlert.datePicker?.maximumDate = NSDate() as Date
            customAlert.datePicker.datePickerMode = .date
            customAlert.datePickerType = DatePickerType(rawValue: 0)
            customAlert.cellType = 0
            customAlert.typeClosure = { (str: String)-> Void in
                model.detail = str
                self.tableView.reloadData()
            }
            customAlert.showAlertView()
        }
        if indexPath.row == 1 {
            let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[0] as! CustomAlterView
            let locale = NSLocale(localeIdentifier: "da_DK")
            customAlert.datePicker?.locale = locale as Locale
            customAlert.datePicker.datePickerMode = .time
            customAlert.datePickerType = DatePickerType(rawValue: 1)
            customAlert.cellType = 0
            customAlert.typeClosure = { (str: String)-> Void in
                model.detail = str
                let type = Common.configureType(type: str)
                (self.dataSource[2] as Model).detail = type
                self.tableView.reloadData()
            }
            let dateformatter = DateFormatter()
            dateformatter.dateFormat = "yyyy-MM-dd"
            let dateString = dateformatter.string(from: Date())
            if(dataSource[0].detail == dateString) {
                //等于今天
                customAlert.datePicker?.maximumDate = NSDate() as Date
            }
            customAlert.showAlertView()
        }
        if indexPath.row == 2 {
            let customAlert = Bundle.main.loadNibNamed("CustomAlertView", owner: nil, options: nil)?[1] as! CustomAlterView
            customAlert.cellType = 0
            customAlert.tmpType = model.detail
            customAlert.typeClosure = { (str: String)-> Void in
                model.detail = str
                self.tableView.reloadData()
            }
            customAlert.showAlertView()
        }
        if indexPath.row == 4 {
            let cell = tableView.cellForRow(at: indexPath)
            cell?.selectionStyle = .none
        }
        
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 4 {
            return 100
        }
        return 60
    }
    
}

